package com.gitee.yannzh.rune.core.util;


import cn.hutool.extra.validation.BeanValidationResult;
import com.gitee.yannzh.rune.core.exception.ServiceException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Yann
 * @date 2019/9/19
 * @description 校验 工具类 参考 cn.hutool.extra.validation.ValidationUtil
 */
public class ValidationUtils {

    private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> void validate(T bean, Class<?>... groups) {
        validateThrow(bean, res -> new ServiceException(
                res.getErrorMessages().stream().map(BeanValidationResult.ErrorMessage::getMessage).collect(Collectors.joining(" \r\n"))
        ), groups);

    }

    public static <T, E extends Throwable> void validateThrow(T bean, Function<BeanValidationResult, E> func, Class<?>... groups) throws E {

        Set<ConstraintViolation<T>> violationSet = validator.validate(bean, groups);
        BeanValidationResult validationResult = warpBeanValidationResult(violationSet);
        if (!validationResult.isSuccess()) {
            throw func.apply(validationResult);
        }
    }

    /**
     * 包装校验结果
     *
     * @param constraintViolations 校验结果集
     * @return {@link BeanValidationResult}
     */
    private static <T> BeanValidationResult warpBeanValidationResult(Set<ConstraintViolation<T>> constraintViolations) {
        BeanValidationResult result = new BeanValidationResult(constraintViolations.isEmpty());
        for (ConstraintViolation<T> constraintViolation : constraintViolations) {
            BeanValidationResult.ErrorMessage errorMessage = new BeanValidationResult.ErrorMessage();
            errorMessage.setPropertyName(constraintViolation.getPropertyPath().toString());
            errorMessage.setMessage(constraintViolation.getMessage());
            errorMessage.setValue(constraintViolation.getInvalidValue());
            result.addErrorMessage(errorMessage);
        }
        return result;
    }

}
